import axios from 'axios'
import {
  Toast
} from 'vant'
// import util from '@/libs/util'
import router from '@/router'
// import fileDownload from 'js-file-download'
// 返回登录页面
function goLogin() {
  const {
    path
  } = router.currentRoute
  if (path !== '/login') {
    router.replace({
      name: 'login'
      // query: {
      //   redirect: path
      // }
    })
  }
}

let resUuid = ''

// 创建一个错误
function errorCreate(msg) {
  setTimeout(() => {
    Toast.fail(msg)
  }, 500)

  const error = new Error(msg)

  errorLog(error)
  throw error
}

// 记录和显示错误

// eslint-disable-next-line handle-callback-err
function errorLog(error) {
  // 打印到控制台
  if (process.env.NODE_ENV === 'development') {
    // 显示提示
    // Toast.fail(error)
  }
}

// 创建一个 axios 实例
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? '/api' : process.env.VUE_APP_API,
  timeout: 9999 // 请求超时时间
})
let times = 0
// 请求拦截器
service.interceptors.request.use(
  config => {
    // 在请求发送之前做一些处理
    times++
    if (!config.url.includes('/upload')) {
      Toast.loading({
        duration: 9999,
        message: '加载中...',
        forbidClick: true
      })
    }
    const token = localStorage.getItem('token')
    if (config.url !== 'api-uaa/oauth/user/login') {
      if (token && token !== 'undefined' && !config.url.includes('api-uaa/oauth/captcha')) {
        config.headers['Authorization'] = token
      }
    } else {
      // 登录接口添加上uuid
      config.headers['uuid'] = resUuid
    }
    config.headers['clientType'] = 'h5'
    return config
  },
  error => {
    // 发送失败
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    times--
    console.log(times)
    if (times === 0) {
      Toast.clear()
    }
    const {
      headers: {
        authorization,
        'content-disposition': contentDisposition,
        uuid
      },
      data: dataAxios
    } = response
    if (authorization) {
      localStorage.setItem('token', authorization)
    }

    // 通过此字段有值，判断为文件下载
    if (contentDisposition) {
      // eslint-disable-next-line no-undef
      fileDownload(
        response.data,
        // 这一波解析，能解决中文名乱码的问题
        decodeURI(escape(contentDisposition.split('=')[1]))
      )
      // 正常返回数据
      return dataAxios
    }

    // 验证码的逻辑处理，登录接口需要用到
    if (uuid) {
      resUuid = uuid
    }
    const {
      statusCode
    } = dataAxios
    switch (statusCode) {
      case 0:
        return dataAxios
      case 401:
        goLogin()
        break
      // 验证码返回数据
      case undefined:
        return dataAxios
      default:
        errorCreate(`${dataAxios.msg}`)
        break
    }
  },
  error => {
    Toast.clear()
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误'
          break
        case 401:
          goLogin()
          error.message = '未授权，请登录'
          break
        case 403:
          error.message = '拒绝访问'
          break
        case 404:
          // error.message = `请求地址出错: ${error.response.config.url}`
          error.message = '请求地址出错'
          break
        case 408:
          error.message = '请求超时'
          break
        case 500:
          error.message = '服务器内部错误'
          break
        case 501:
          error.message = '服务未实现'
          break
        case 502:
          error.message = '网关错误'
          break
        case 503:
          error.message = '服务不可用'
          break
        case 504:
          error.message = '网关超时'
          break
        case 505:
          error.message = 'HTTP版本不受支持'
          break
        default:
          break
      }
    }
    // errorLog(error)
    Toast.fail(error.message)
    // router.push('/login')
    return Promise.reject(error)
  }
)
export default service
